@{
    ViewData["Title"] = "不良品汇总";
}

@section Styles {
    <link rel="stylesheet" href="~/css/defective-summary.css">
    <style>
        /* 页面整体样式 */
        .layui-fluid {
            padding: 20px;
            background-color: #f5f5f5;
        }

        /* 卡片样式 */
        .layui-card {
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            border: none;
            margin-bottom: 20px;
        }

        .layui-card-body {
            background-color: white;
        }

        /* 查询表单样式 */
        .search-form {
            background: #fafafa;
            padding: 20px;
            border-radius: 6px;
            margin-bottom: 20px;
        }

        .search-form .layui-form-item {
            margin-bottom: 15px;
        }

        /* 高级查询折叠面板 */
        .advanced-search {
            background: #f9f9f9;
            border: 1px solid #e6e6e6;
            border-radius: 6px;
            margin-top: 15px;
            overflow: hidden;
        }

        .advanced-search-header {
            padding: 12px 20px;
            background: #eeeeee;
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-weight: 500;
        }

        .advanced-search-header:hover {
            background: #e6e6e6;
        }

        .advanced-search-content {
            padding: 20px;
            display: none;
        }

        .advanced-search-content.show {
            display: block;
        }

        .toggle-icon {
            transition: transform 0.3s ease;
        }

        .toggle-icon.rotate {
            transform: rotate(180deg);
        }

        /* 表格样式 */
        .layui-table {
            border-radius: 6px;
            overflow: hidden;
        }

        .layui-table thead tr {
            background-color: #fafafa;
        }

        .layui-table tbody tr:hover {
            background-color: #f8f9fa;
        }

        /* 按钮样式 */
        .layui-btn {
            border-radius: 6px;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .layui-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        /* 输入框样式 */
        .layui-input, .layui-select {
            border-radius: 6px;
            border: 1px solid #e6e6e6;
            transition: border-color 0.3s ease;
        }

        .layui-input:focus, .layui-select:focus {
            border-color: #1E9FFF;
            box-shadow: 0 0 0 2px rgba(30, 159, 255, 0.2);
        }

        /* 工具栏样式 */
        .toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        /* 统计信息样式 */
        .stats-info {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        .stats-item {
            text-align: center;
        }

        .stats-number {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 5px;
        }

        .stats-label {
            font-size: 14px;
            opacity: 0.9;
        }

        /* 表格列宽设置 */
        .table-container {
            overflow-x: auto;
        }

        #defectiveSummaryTable th:nth-child(1) { width: 50px; }
        #defectiveSummaryTable th:nth-child(2) { width: 120px; }
        #defectiveSummaryTable th:nth-child(3) { width: 100px; }
        #defectiveSummaryTable th:nth-child(4) { width: 120px; }
        #defectiveSummaryTable th:nth-child(5) { width: 100px; }
        #defectiveSummaryTable th:nth-child(6) { width: 80px; }
        #defectiveSummaryTable th:nth-child(7) { width: 120px; }
        #defectiveSummaryTable th:nth-child(8) { width: 120px; }
        #defectiveSummaryTable th:nth-child(9) { width: 100px; }
        #defectiveSummaryTable th:nth-child(10) { width: 80px; }
        #defectiveSummaryTable th:nth-child(11) { width: 80px; }
        #defectiveSummaryTable th:nth-child(12) { width: 80px; }
        #defectiveSummaryTable th:nth-child(13) { width: 80px; }

        /* 响应式设计 */
        @@media (max-width: 768px) {
            .layui-fluid {
                padding: 10px;
            }
            
            .search-form {
                padding: 15px;
            }
            
            .toolbar {
                flex-direction: column;
                gap: 10px;
            }
        }
    </style>
}

<div class="layui-fluid">
    <!-- 页面标题 -->
    <div class="layui-card">
        <div class="layui-card-body">
            <h2 style="margin: 0; color: #333;">
                <i class="layui-icon layui-icon-chart" style="color: #1E9FFF;"></i>
                不良品汇总
            </h2>
        </div>
    </div>

    <!-- 查询表单 -->
    <div class="layui-card">
        <div class="layui-card-body">
            <form class="layui-form search-form" lay-filter="searchForm">
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label">工单编号</label>
                            <div class="layui-input-block">
                                <input type="text" name="workOrderCode" placeholder="请输入工单编号" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <div class="layui-input-block" style="margin-left: 0;">
                                <button type="button" class="layui-btn" id="searchBtn">
                                    <i class="layui-icon layui-icon-search"></i> 查询
                                </button>
                                <button type="button" class="layui-btn layui-btn-primary" id="resetBtn">
                                    <i class="layui-icon layui-icon-refresh"></i> 重置
                                </button>
                                <button type="button" class="layui-btn layui-btn-normal" id="exportBtn">
                                    <i class="layui-icon layui-icon-export"></i> 导出
                                </button>
                                <button type="button" class="layui-btn layui-btn-warm" id="settingsBtn">
                                    <i class="layui-icon layui-icon-set"></i> 设置
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 高级查询 -->
                <div class="advanced-search">
                    <div class="advanced-search-header" id="advancedToggle">
                        <span>高级查询</span>
                        <i class="layui-icon layui-icon-down toggle-icon" id="toggleIcon"></i>
                    </div>
                    <div class="advanced-search-content" id="advancedContent">
                        <div class="layui-row layui-col-space15">
                            <div class="layui-col-md4">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">产品编号</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="productCode" placeholder="请输入产品编号" class="layui-input">
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-md4">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">产品名称</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="productName" placeholder="请输入产品名称" class="layui-input">
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-md4">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">工序编号</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="processCode" placeholder="请输入工序编号" class="layui-input">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="layui-row layui-col-space15">
                            <div class="layui-col-md4">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">工序名称</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="processName" placeholder="请输入工序名称" class="layui-input">
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-md4">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">生产人员</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="producer" placeholder="请输入生产人员" class="layui-input">
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-md4">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">不良品项</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="defectiveItem" placeholder="请输入不良品项" class="layui-input">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="layui-row layui-col-space15">
                            <div class="layui-col-md6">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">生产开始时间</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="productionStartTimeBegin" placeholder="开始时间" class="layui-input" id="startTimeBegin">
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-md6">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">至</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="productionStartTimeEnd" placeholder="结束时间" class="layui-input" id="startTimeEnd">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="layui-row layui-col-space15">
                            <div class="layui-col-md6">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">生产结束时间</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="productionEndTimeBegin" placeholder="开始时间" class="layui-input" id="endTimeBegin">
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-md6">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">至</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="productionEndTimeEnd" placeholder="结束时间" class="layui-input" id="endTimeEnd">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="layui-row layui-col-space15">
                            <div class="layui-col-md3">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">报工数量</label>
                                    <div class="layui-input-block">
                                        <input type="number" name="reportQuantityMin" placeholder="最小值" class="layui-input">
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-md3">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">至</label>
                                    <div class="layui-input-block">
                                        <input type="number" name="reportQuantityMax" placeholder="最大值" class="layui-input">
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-md3">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">合格数量</label>
                                    <div class="layui-input-block">
                                        <input type="number" name="qualifiedQuantityMin" placeholder="最小值" class="layui-input">
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-md3">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">至</label>
                                    <div class="layui-input-block">
                                        <input type="number" name="qualifiedQuantityMax" placeholder="最大值" class="layui-input">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- 统计信息 -->
    <div class="stats-info" id="statsInfo" style="display: none;">
        <div class="layui-row">
            <div class="layui-col-md3">
                <div class="stats-item">
                    <div class="stats-number" id="totalRecords">0</div>
                    <div class="stats-label">总记录数</div>
                </div>
            </div>
            <div class="layui-col-md3">
                <div class="stats-item">
                    <div class="stats-number" id="totalDefective">0</div>
                    <div class="stats-label">总不良数量</div>
                </div>
            </div>
            <div class="layui-col-md3">
                <div class="stats-item">
                    <div class="stats-number" id="avgDefectiveRate">0%</div>
                    <div class="stats-label">平均不良率</div>
                </div>
            </div>
            <div class="layui-col-md3">
                <div class="stats-item">
                    <div class="stats-number" id="totalReportQuantity">0</div>
                    <div class="stats-label">总报工数量</div>
                </div>
            </div>
        </div>
    </div>

    <!-- 数据表格 -->
    <div class="layui-card">
        <div class="layui-card-body">
            <div class="table-container">
                <table class="layui-table" lay-filter="defectiveSummaryTable" id="defectiveSummaryTable">
                    <thead id="tableHeader">
                        <!-- 动态生成表头 -->
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
            
            <!-- 分页 -->
            <div id="pagination"></div>
        </div>
    </div>
</div>

<!-- 模板 -->
<script type="text/html" id="timeTpl">
    {{# if(d.productionStartTime || d.productionEndTime) { }}
        {{ layui.util.toDateString(new Date(d.productionStartTime || d.productionEndTime), 'yyyy-MM-dd HH:mm') }}
    {{# } else { }}
        -
    {{# } }}
</script>

<script type="text/html" id="rateTpl">
    {{# if(d.defectiveRate !== null && d.defectiveRate !== undefined) { }}
        <span style="color: {{ d.defectiveRate > 10 ? '#ff5722' : (d.defectiveRate > 5 ? '#ff9800' : '#4caf50') }};">
            {{ d.defectiveRate.toFixed(2) }}%
        </span>
    {{# } else { }}
        -
    {{# } }}
</script>

@section Scripts {
    <script>
        layui.use(['table', 'form', 'laydate', 'layer', 'laypage'], function(){
            var table = layui.table,
                form = layui.form,
                laydate = layui.laydate,
                layer = layui.layer,
                laypage = layui.laypage,
                $ = layui.$;

            var readApiUrl = '@ViewBag.ReadApiUrl';
            var currentPage = 1;
            var pageSize = 10;
            var totalCount = 0;

            // 初始化日期选择器
            laydate.render({
                elem: '#startTimeBegin',
                type: 'datetime'
            });
            laydate.render({
                elem: '#startTimeEnd',
                type: 'datetime'
            });
            laydate.render({
                elem: '#endTimeBegin',
                type: 'datetime'
            });
            laydate.render({
                elem: '#endTimeEnd',
                type: 'datetime'
            });

            // 高级查询折叠展开
            $('#advancedToggle').click(function(){
                var content = $('#advancedContent');
                var icon = $('#toggleIcon');
                
                if(content.hasClass('show')){
                    content.removeClass('show');
                    icon.removeClass('rotate');
                } else {
                    content.addClass('show');
                    icon.addClass('rotate');
                }
            });

            // 处理排序
            function handleSort(field) {
                if (currentSort.field === field) {
                    // 同一列：切换排序方向
                    if (currentSort.order === 'asc') {
                        currentSort.order = 'desc';
                    } else if (currentSort.order === 'desc') {
                        // 取消排序
                        currentSort.field = null;
                        currentSort.order = null;
                    } else {
                        currentSort.order = 'asc';
                    }
                } else {
                    // 新列：默认升序
                    currentSort.field = field;
                    currentSort.order = 'asc';
                }
                
                // 重新加载数据
                loadData(1);
            }

            // 加载数据
            function loadData(page) {
                page = page || 1;
                var formData = form.val('searchForm');
                
                var params = Object.assign({}, formData, {
                    pageIndex: page,
                    pageSize: pageSize
                });

                // 添加排序参数
                if (currentSort.field && currentSort.order) {
                    params.sortField = currentSort.field;
                    params.sortOrder = currentSort.order;
                }

                // 移除空值
                Object.keys(params).forEach(key => {
                    if (params[key] === '' || params[key] === null || params[key] === undefined) {
                        delete params[key];
                    }
                });

                layer.load(1);
                
                $.ajax({
                    url: '/DefectiveSummary/GetDefectiveSummary',
                    type: 'GET',
                    data: params,
                    success: function(response) {
                        layer.closeAll('loading');
                        
                        if(response && response.code === 200) {
                            var data = response.pageData || [];
                            totalCount = response.totaCount || 0;
                            currentPage = page;
                            
                            // 渲染表格数据
                            renderTable(data);
                            
                            // 渲染分页
                            renderPagination();
                            
                            // 更新统计信息
                            updateStats(data, totalCount);
                            
                            layer.msg('查询成功', {icon: 1, time: 1000});
                        } else {
                            layer.msg(response.msg || '查询失败', {icon: 2});
                            renderTable([]);
                            renderPagination();
                        }
                    },
                    error: function(xhr, status, error) {
                        layer.closeAll('loading');
                        layer.msg('网络错误：' + error, {icon: 2});
                        renderTable([]);
                        renderPagination();
                    }
                });
            }

            // 当前排序状态
            var currentSort = {
                field: null,
                order: null // 'asc' 或 'desc'
            };

            // 渲染表格头
            function renderTableHeader() {
                var config = getSavedColumnConfig();
                var visibleColumns = config.filter(col => col.show !== false);
                
                var headerHtml = '<tr>';
                visibleColumns.forEach(function(col) {
                    var sortIcon = '';
                    var sortClass = '';
                    
                    // 添加排序图标
                    if (currentSort.field === col.field) {
                        if (currentSort.order === 'asc') {
                            sortIcon = '<i class="layui-icon layui-icon-triangle-d sort-icon active"></i>';
                            sortClass = ' sorted-asc';
                        } else if (currentSort.order === 'desc') {
                            sortIcon = '<i class="layui-icon layui-icon-triangle-r sort-icon active"></i>';
                            sortClass = ' sorted-desc';
                        }
                    } else {
                        sortIcon = '<i class="layui-icon layui-icon-triangle-d sort-icon"></i>';
                    }
                    
                    headerHtml += '<th class="sortable-header' + sortClass + '" data-field="' + col.field + '" style="width: ' + col.width + 'px; cursor: pointer; user-select: none; position: relative;">' + 
                                  col.title + ' ' + sortIcon + '</th>';
                });
                headerHtml += '</tr>';
                
                $('#tableHeader').html(headerHtml);
                
                // 为表头添加点击排序事件
                $('#tableHeader th.sortable-header').click(function() {
                    var field = $(this).data('field');
                    handleSort(field);
                });
            }

            // 渲染表格
            function renderTable(data) {
                // 先渲染表头
                renderTableHeader();
                
                var tbody = $('#defectiveSummaryTable tbody');
                tbody.empty();
                
                var config = getSavedColumnConfig();
                var visibleColumns = config.filter(col => col.show !== false);
                
                if(data.length === 0) {
                    tbody.append('<tr><td colspan="' + visibleColumns.length + '" style="text-align: center; padding: 50px;">暂无数据</td></tr>');
                    return;
                }
                
                data.forEach(function(item) {
                    var tr = $('<tr></tr>');
                    
                    // 格式化时间
                    var formatTime = function(timeStr) {
                        if(!timeStr) return '-';
                        return new Date(timeStr).toLocaleString('zh-CN', {
                            year: 'numeric',
                            month: '2-digit',
                            day: '2-digit',
                            hour: '2-digit',
                            minute: '2-digit'
                        });
                    };
                    
                    // 格式化不良率颜色
                    var formatRate = function(rate) {
                        if(rate === null || rate === undefined) return '-';
                        var color = rate > 10 ? '#ff5722' : (rate > 5 ? '#ff9800' : '#4caf50');
                        return '<span style="color: ' + color + ';">' + rate.toFixed(2) + '%</span>';
                    };
                    
                    // 根据列配置动态生成单元格
                    var cellsHtml = '';
                    visibleColumns.forEach(function(col) {
                        var value = '';
                        switch(col.field) {
                            case 'id':
                                value = item.id || '-';
                                break;
                            case 'workOrderCode':
                                value = item.workOrderCode || '-';
                                break;
                            case 'productCode':
                                value = item.productCode || '-';
                                break;
                            case 'productName':
                                value = item.productName || '-';
                                break;
                            case 'processName':
                                value = item.processName || '-';
                                break;
                            case 'producer':
                                value = item.producer || '-';
                                break;
                            case 'productionStartTime':
                                value = formatTime(item.productionStartTime);
                                break;
                            case 'productionEndTime':
                                value = formatTime(item.productionEndTime);
                                break;
                            case 'defectiveItem':
                                value = item.defectiveItem || '-';
                                break;
                            case 'reportQuantity':
                                value = item.reportQuantity || 0;
                                break;
                            case 'qualifiedQuantity':
                                value = item.qualifiedQuantity || 0;
                                break;
                            case 'defectiveQuantity':
                                value = item.defectiveQuantity || 0;
                                break;
                            case 'defectiveRate':
                                value = formatRate(item.defectiveRate);
                                break;
                            default:
                                value = '-';
                        }
                        cellsHtml += '<td>' + value + '</td>';
                    });
                    
                    tr.html(cellsHtml);
                    tbody.append(tr);
                });
            }

            // 渲染分页
            function renderPagination() {
                if(totalCount === 0) {
                    $('#pagination').empty();
                    return;
                }
                
                laypage.render({
                    elem: 'pagination',
                    count: totalCount,
                    curr: currentPage,
                    limit: pageSize,
                    limits: [10, 20, 50, 100],
                    layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
                    jump: function(obj, first) {
                        pageSize = obj.limit;
                        if(!first) {
                            loadData(obj.curr);
                        }
                    }
                });
            }

            // 更新统计信息
            function updateStats(data, total) {
                if(data.length === 0) {
                    $('#statsInfo').hide();
                    return;
                }
                
                var totalDefectiveQuantity = data.reduce((sum, item) => sum + (item.defectiveQuantity || 0), 0);
                var totalReportQuantity = data.reduce((sum, item) => sum + (item.reportQuantity || 0), 0);
                var avgDefectiveRate = data.length > 0 ? 
                    data.reduce((sum, item) => sum + (item.defectiveRate || 0), 0) / data.length : 0;
                
                $('#totalRecords').text(total);
                $('#totalDefective').text(totalDefectiveQuantity);
                $('#avgDefectiveRate').text(avgDefectiveRate.toFixed(2) + '%');
                $('#totalReportQuantity').text(totalReportQuantity);
                
                $('#statsInfo').show();
            }

            // 查询按钮事件
            $('#searchBtn').click(function() {
                loadData(1);
            });

            // 重置按钮事件
            $('#resetBtn').click(function() {
                // 清空所有输入框
                $('form[lay-filter="searchForm"] input[type="text"]').val('');
                
                // 清空时间选择器
                $('#startTimeBegin').val('');
                $('#startTimeEnd').val('');
                $('#endTimeBegin').val('');
                $('#endTimeEnd').val('');
                
                // 使用layui form重置
                form.val('searchForm', {
                    workOrderCode: '',
                    productCode: '',
                    productName: '',
                    processCode: '',
                    processName: '',
                    producer: '',
                    defectiveItem: '',
                    productionStartTimeBegin: '',
                    productionStartTimeEnd: '',
                    productionEndTimeBegin: '',
                    productionEndTimeEnd: ''
                });
                
                // 重新渲染表单（确保所有组件都被重置）
                form.render();
                
                // 重置到第一页并加载数据
                currentPage = 1;
                loadData(1);
            });

            // 导出按钮事件
            $('#exportBtn').click(function() {
                var formData = form.val('searchForm');
                
                // 移除空值
                Object.keys(formData).forEach(key => {
                    if (formData[key] === '' || formData[key] === null || formData[key] === undefined) {
                        delete formData[key];
                    }
                });
                
                var queryString = $.param(formData);
                var exportUrl = '/DefectiveSummary/ExportDefectiveSummary' + (queryString ? '?' + queryString : '');
                
                layer.confirm('确定要导出当前查询条件下的数据吗？', {
                    btn: ['确定', '取消']
                }, function(index) {
                    layer.close(index);
                    layer.msg('正在导出，请稍候...', {icon: 16, time: 2000});
                    window.open(exportUrl, '_blank');
                });
            });

            // 设置按钮事件
            $('#settingsBtn').click(function() {
                openColumnSettings();
            });

            // 将loadData函数暴露到全局作用域以供列设置使用
            window.refreshDefectiveTable = function() {
                loadData(currentPage);
            };

            // 页面加载时渲染表头并自动查询
            renderTableHeader();
            loadData(1);
        });

        // 列配置管理
        var defaultColumns = [
            { field: 'id', title: 'ID', width: 50, fixed: true, order: 1 },
            { field: 'workOrderCode', title: '工单编号', width: 120, order: 2 },
            { field: 'productCode', title: '产品编号', width: 100, order: 3 },
            { field: 'productName', title: '产品名称', width: 120, order: 4 },
            { field: 'processName', title: '工序名称', width: 100, order: 5 },
            { field: 'producer', title: '生产人员', width: 80, order: 6 },
            { field: 'productionStartTime', title: '生产开始时间', width: 120, order: 7 },
            { field: 'productionEndTime', title: '生产结束时间', width: 120, order: 8 },
            { field: 'defectiveItem', title: '不良品项', width: 100, order: 9 },
            { field: 'reportQuantity', title: '报工数量', width: 80, order: 10 },
            { field: 'qualifiedQuantity', title: '合格数量', width: 80, order: 11 },
            { field: 'defectiveQuantity', title: '不良数量', width: 80, order: 12 },
            { field: 'defectiveRate', title: '不良率(%)', width: 80, order: 13 }
        ];

        // 获取保存的列配置
        function getSavedColumnConfig() {
            var saved = localStorage.getItem('defectiveSummary_columnConfig');
            if (saved) {
                try {
                    var config = JSON.parse(saved);
                    // 确保所有列都有order属性，如果没有则按照默认顺序设置
                    config = config.map(function(col, index) {
                        if (!col.order) {
                            col.order = index + 1;
                        }
                        return col;
                    });
                    // 按order排序
                    config.sort(function(a, b) {
                        return a.order - b.order;
                    });
                    return config;
                } catch (e) {
                    return defaultColumns;
                }
            }
            return defaultColumns;
        }

        // 保存列配置
        function saveColumnConfig(config) {
            localStorage.setItem('defectiveSummary_columnConfig', JSON.stringify(config));
        }

        // 打开列设置弹窗
        function openColumnSettings() {
            var currentConfig = getSavedColumnConfig();
            var content = buildColumnSettingsContent(currentConfig);
            
            layer.open({
                type: 1,
                title: '列设置',
                area: ['500px', '600px'],
                content: content,
                btn: ['保存', '重置', '取消'],
                btn1: function(index) {
                    saveColumnSettings();
                    layer.close(index);
                    // 重新加载表格
                    if (typeof window.refreshDefectiveTable === 'function') {
                        window.refreshDefectiveTable();
                    }
                },
                btn2: function() {
                    resetColumnSettings();
                    return false; // 不关闭弹窗
                },
                success: function(layero) {
                    // 初始化表单
                    layui.use('form', function() {
                        var form = layui.form;
                        form.render();
                    });
                    
                    // 初始化拖拽功能
                    initDragAndDrop();
                }
            });
        }

        // 构建列设置内容
        function buildColumnSettingsContent(config) {
            var html = '<div class="column-settings" style="padding: 20px;">';
            html += '<div class="column-settings-tip">拖动列名可调整表格列显示顺序，勾选显示列，取消勾选隐藏列</div>';
            html += '<table class="layui-table" style="margin: 0;">';
            html += '<thead>';
            html += '<tr>';
            html += '<th style="width: 40px;">#</th>';
            html += '<th>列名</th>';
            html += '<th style="width: 100px;">是否显示</th>';
            html += '</tr>';
            html += '</thead>';
            html += '<tbody id="columnSettingsBody">';
            
            config.forEach(function(col, index) {
                var checked = col.show !== false ? 'checked' : '';
                var disabled = col.fixed ? 'disabled' : '';
                html += '<tr data-field="' + col.field + '" draggable="true">';
                html += '<td class="drag-handle layui-icon layui-icon-more-vertical" style="cursor: move; text-align: center; color: #999;"></td>';
                html += '<td class="column-name">' + col.title + '</td>';
                html += '<td style="text-align: center;">';
                html += '<input type="checkbox" ' + checked + ' ' + disabled + ' lay-filter="columnShow" data-field="' + col.field + '">';
                html += '</td>';
                html += '</tr>';
            });
            
            html += '</tbody>';
            html += '</table>';
            html += '</div>';
            return html;
        }

        // 初始化拖拽功能
        function initDragAndDrop() {
            // 首先尝试加载SortableJS库
            if (typeof Sortable === 'undefined') {
                // 动态加载SortableJS
                var script = document.createElement('script');
                script.src = 'https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js';
                script.onload = function() {
                    setupSortable();
                };
                script.onerror = function() {
                    // 如果加载失败，使用原生HTML5拖拽
                    setupNativeDragDrop();
                };
                document.head.appendChild(script);
            } else {
                setupSortable();
            }
        }

        // 使用SortableJS设置拖拽
        function setupSortable() {
            var tbody = document.getElementById('columnSettingsBody');
            if (tbody) {
                new Sortable(tbody, {
                    handle: '.drag-handle',
                    animation: 150,
                    onEnd: function() {
                        updateColumnOrder();
                    }
                });
            }
        }

        // 使用原生HTML5拖拽作为备选方案
        function setupNativeDragDrop() {
            var tbody = $('#columnSettingsBody');
            var dragEl = null;

            tbody.find('tr').each(function() {
                var $row = $(this);
                
                this.addEventListener('dragstart', function(e) {
                    dragEl = this;
                    this.classList.add('dragging');
                    e.dataTransfer.effectAllowed = 'move';
                });
                
                this.addEventListener('dragend', function() {
                    this.classList.remove('dragging');
                    updateColumnOrder();
                });
                
                this.addEventListener('dragover', function(e) {
                    e.preventDefault();
                    var after = getDragAfterElement(tbody[0], e.clientY);
                    if (!after) {
                        tbody[0].appendChild(dragEl);
                    } else {
                        tbody[0].insertBefore(dragEl, after);
                    }
                });
            });
        }

        // 获取拖拽后的位置元素
        function getDragAfterElement(container, y) {
            var els = [...container.querySelectorAll('tr:not(.dragging)')];
            return els.reduce(function(closest, child) {
                var box = child.getBoundingClientRect();
                var offset = y - box.top - box.height / 2;
                if (offset < 0 && offset > closest.offset) {
                    return { offset: offset, element: child };
                } else {
                    return closest;
                }
            }, { offset: Number.NEGATIVE_INFINITY }).element;
        }

        // 更新列顺序
        function updateColumnOrder() {
            $('#columnSettingsBody tr').each(function(index) {
                var field = $(this).data('field');
                // 更新列配置中的order属性
                defaultColumns.forEach(function(col) {
                    if (col.field === field) {
                        col.order = index + 1;
                    }
                });
            });
        }

        // 刷新表格
        function refreshTable() {
            // 重新加载当前页数据
            if (typeof window.refreshDefectiveTable === 'function') {
                window.refreshDefectiveTable();
            }
        }

        // 保存列设置
        function saveColumnSettings() {
            var newConfig = [];
            
            // 按照当前拖拽后的顺序保存配置
            $('#columnSettingsBody tr').each(function(index) {
                var field = $(this).data('field');
                var checkbox = $(this).find('input[type="checkbox"]');
                
                // 从默认配置中找到对应的列
                var originalCol = defaultColumns.find(function(col) {
                    return col.field === field;
                });
                
                if (originalCol) {
                    var newCol = Object.assign({}, originalCol);
                    newCol.show = checkbox.is(':checked');
                    newCol.order = index + 1;
                    newConfig.push(newCol);
                }
            });
            
            saveColumnConfig(newConfig);
            layer.msg('列设置已保存', {icon: 1});
            
            // 立即刷新表格以显示新的列配置
            setTimeout(function() {
                if (typeof window.refreshDefectiveTable === 'function') {
                    window.refreshDefectiveTable();
                }
            }, 500); // 延迟500ms让用户看到保存提示
        }

        // 重置列设置
        function resetColumnSettings() {
            layer.confirm('确定要重置为默认列设置吗？', function(index) {
                saveColumnConfig(defaultColumns);
                layer.close(index);
                layer.msg('已重置为默认设置', {icon: 1});
                
                // 立即刷新表格以显示默认列配置
                setTimeout(function() {
                    if (typeof window.refreshDefectiveTable === 'function') {
                        window.refreshDefectiveTable();
                    }
                }, 500);
                
                // 重新打开设置窗口
                setTimeout(function() {
                    openColumnSettings();
                }, 1000);
            });
        }
    </script>

    <!-- 列设置样式 -->
    <style>
        .column-settings {
            padding: 20px;
        }
        
        .column-settings-tip {
            background: #f0f9ff;
            border: 1px solid #bfdbfe;
            border-radius: 4px;
            padding: 10px;
            margin-bottom: 15px;
            color: #1e40af;
            font-size: 12px;
        }
        
        .column-list {
            max-height: 400px;
            overflow-y: auto;
        }
        
        .column-item {
            display: flex;
            align-items: center;
            padding: 8px 12px;
            border: 1px solid #e5e7eb;
            border-radius: 4px;
            margin-bottom: 5px;
            background: #fff;
        }
        
        .column-item:hover {
            background: #f9fafb;
            border-color: #d1d5db;
        }

        /* 拖拽相关样式 */
        .drag-handle {
            cursor: move;
            color: #999;
            font-size: 14px;
            padding: 5px;
            transition: color 0.2s;
        }

        .drag-handle:hover {
            color: #1890ff;
        }

        #columnSettingsBody tr {
            transition: background-color 0.2s;
        }

        #columnSettingsBody tr:hover {
            background-color: #f8f9fa;
        }

        #columnSettingsBody tr.dragging {
            opacity: 0.5;
            background-color: #e6f7ff;
        }

        .sortable-ghost {
            opacity: 0.4;
            background-color: #f0f0f0;
        }

        .sortable-chosen {
            background-color: #e6f7ff;
        }

        .sortable-drag {
            opacity: 0.8;
            background-color: #fff;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
        }

        /* 列设置表格样式优化 */
        .column-settings .layui-table th,
        .column-settings .layui-table td {
            padding: 8px 12px;
            text-align: center;
        }

        .column-settings .layui-table th:first-child,
        .column-settings .layui-table td:first-child {
            text-align: center;
        }

        .column-settings .layui-table td:nth-child(2) {
            text-align: left;
            font-weight: 500;
        }

        /* 排序相关样式 */
        .sortable-header {
            transition: background-color 0.2s;
        }

        .sortable-header:hover {
            background-color: #f8f9fa !important;
        }

        .sort-icon {
            font-size: 12px;
            margin-left: 5px;
            color: #ccc;
            transform: rotate(180deg);
            transition: color 0.2s, transform 0.2s;
        }

        .sort-icon.active {
            color: #1890ff;
        }

        .sorted-desc .sort-icon {
            transform: rotate(90deg);
        }

        .sorted-asc .sort-icon {
            transform: rotate(180deg);
        }

        .sortable-header.sorted-asc,
        .sortable-header.sorted-desc {
            background-color: #e6f7ff !important;
        }
        
        .column-checkbox {
            margin-right: 10px;
        }
        
        .column-title {
            flex: 1;
            font-size: 14px;
        }
    </style>
} 